/*
 * Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
 */
package com.xinpan.exercise;

public class SpiralMatrix2 {
    public int[][] generateMatrix(int n) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int l = n;
        int[][] matrix = new int[l][l];
        
        
        int c = 1;
        int i = 0;
        for(; i < l/2; i++)
        {
            for(int j = i; j < l-i; j++)
                matrix[i][j] = c++;
            for(int j = i+1; j < l-i; j++)
                matrix[j][l-i-1] = c++;
            for(int j = l-i-2; j >= i; j--)
                matrix[l-i-1][j] = c++;
            for(int j = l-i-2; j >= i+1; j--)
                matrix[j][i] = c++;
        }
        
        if(l % 2 == 1)
            matrix[i][i] = c;
        return matrix;
    }
}
